﻿#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable : 6031)
#include "sl.h"

void printsl(sl* phead)
{
	while (phead)		//这里不是我们的next作为判断，是结构体作为判断
	{					//如果我们的结构体地址=0就不进去了
		printf("%d ", phead->data);
		phead = phead->next;
	}
}

sl* creatsl(int x)
{
	sl* now = (sl*)malloc(sizeof(sl));
	if (!now)
	{
		perror("malloc");
		return NULL;
	}
	now->data = x;
	now->next = NULL;
	return now;
}

void pushback(sl** phead, int x)
{
	assert(phead);
	sl* now = creatsl(x);
	//没有结构体
	if (!( * phead))
	{
		*phead = now;
	}
	//有结构体
	else
	{
		sl* tail = *phead;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = now;
	}
}

void pushfront(sl** phead, int x)
{
	assert(phead);
	sl* now = creatsl(x);
	//没有结构体
	if (!(*phead))
	{
		*phead = now;
	}
	else
	{
		now->next = *phead;
		*phead = now;
	}
}

void popback(sl** phead)
{
	assert(phead);
	assert(*phead);
	if (!((*phead)->next))		//只有一个
	{
		free(*phead);
		*phead = NULL;
	}
	else
	{
		sl* tail = *phead;
		while (tail->next->next)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}

void popfront(sl** phead)
{
	assert(phead);
	assert(*phead);
	if (!((*phead)->next))		//只有一个
	{
		free(*phead);
		*phead = NULL;
	}
	else
	{
		sl* tail = *phead;
		*phead = (*phead)->next;
		free(tail);
	}
}

sl* findsl(sl* phead, int x)
{
	sl* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void insertsl(sl** phead, sl* pos, int x)
{
	assert(pos);
	assert(phead);
	if (*phead == pos)
	{
		pushfront(phead, x);
	}
	else
	{
		sl* tail = creatsl(x);
		sl* sur = *phead;
		while (sur->next != pos)
		{
			sur = sur->next;
		}
		tail->next = pos;
		sur->next = tail;
	}
}

void erase(sl** phead, sl* pos)
{
	assert(phead);
	assert(pos);
	if (!(*phead)->next)
	{
		popfront(phead);
	}
	else
	{
		sl* tail = *phead;
		while (tail->next != pos)
		{
			tail = tail->next;
		}
		tail->next = pos->next;
		free(pos);
	}
}

void eraseafter(sl* pos)
{
	assert(pos);
	assert(pos->next);
	//pos->next = pos->next->next;
	//free(pos->next);	//你这里确定是free的是你想的吗？？ 为什么不写一个标记
	
	sl* tail = pos->next;
	pos->next = tail->next;
	free(tail);
}